<template>
  <div class="layout-padding row justify-center">
    <div style="width: 600px; max-width: 100vw;">
      <q-list >
        <q-list-header>基础信息</q-list-header>
        <q-item>
             <div class="row flex-center" style="width: 100%; height: 80px;">
                <!-- <vue-core-image-upload 
                    style="font-size: 24px;color: #254b32" 
                    :crop="true" 
                    @imageuploaded="setLogoResAction" 
                    :cropBtn="{ok:'确定上传','cancel':'取消'}" 
                    :maxFileSize="5242880" 
                    text="选择图片" 
                    :url="baseResUpUrl" 
                    extensions="png,gif,jpeg,jpg">
                    <img :src="(customer.logoRes || 'statics/hg-logo-camera.png') | avatarView"
                      style="height: 75px;width:75px;border-radius: 50%;"/>
                </vue-core-image-upload> -->
                <avatar-edit-compo v-on:get-file="uploadAvatarPic">
                  <img slot="selectfile" :src="(customer.logoRes || 'statics/hg-logo-camera.png') | avatarView"
                    style="height: 75px;width:75px;border-radius: 50%;"/>
                </avatar-edit-compo>
             </div>
        </q-item>
        <q-item-separator/>
        <q-item>
            <q-field
                icon="account_circle"
                label="昵称"
                :count="16"
              >
              <q-input v-model.trim="customer.nickname" max-length=16  
                :after="[{icon: 'send', content: true, handler:updateNickname }]"/>
            </q-field>
        </q-item>
         <q-item>
             <q-item-main>
            <q-field
                icon="border color"
                :count="128"
              >
              <q-input v-model.trim="customer.summary" 
              max-length=128
              placeholder="个性签名"
              type="textarea"
              :after="[{icon: 'send', content: true, handler:updateSummary }]"/>
            </q-field>
             </q-item-main>
        </q-item>
          
        <q-item>
          <q-item-side icon="supervisor_account" />
          <q-item-main>
                   <q-select
                    float-label="性别象征"
                    v-model="customer.sex"
                    :options="sexOptions"
                    class="full-width" 
                    @change="updateSex"
                  />
          </q-item-main>
        </q-item>
        <q-collapsible  icon="vpn key" label="密码更改" v-if="customer.enabledPwd">
            <q-card>
              <q-card-main>
                <q-field label="原密码"  :error="originPwdError"  error-label="原始密码不能为空">
                      <q-input v-model="changePwdDto.originPwd" @blur="changePwdCheckOrg"  type="password" max-length="16"/>
                </q-field>
                <q-field label="新密码" :error="newPwdError"  error-label="密码请保持在6-16位之间">
                      <q-input v-model="changePwdDto.newPwd" @blur="changePwdCheckNew" type="password"  max-length="16"/>
                </q-field>
                <q-btn
                    color="primary"
                    push
                    @click="changePwdAction"
                    class="full-width"
                    icon="group"
                  > 提交 </q-btn>
              </q-card-main>
          </q-card>
        </q-collapsible>
        <q-item v-else>
            <q-field
                    icon="vpn key"
                    label="密码设定"
                    :error="pwdsetError"
                    error-label="密码请保持在6-16位之间"
                  >
              <q-input v-model.trim="pwdset"  type="password"  :after="[{icon: 'send', content: true, handler:setpwd}]"/>
            </q-field>
        </q-item>

        <q-collapsible  icon="perm phone msg" label="手机号更改">
              <q-card>
                <q-card-main>
                  <mobile-captcha-compo isOriginMobile v-on:callback-phoneinfo="updateMobile"/>
                </q-card-main>
            </q-card>
        </q-collapsible>
        <q-collapsible  icon="email" label="邮箱绑定">
          <q-card>
              <q-card-main class="row">
                 <q-field
                    :error="emailError"
                    error-label="邮箱地址6-16位以内非空字符"
                    class="col-xs-12 col-sm-8"
                  >
                    <q-input  v-model.trim="emailSend" @blur="checkSendEmail" float-label="邮箱" max-length="16" type="email" />
                  </q-field>
                <q-select class="col-xs-12 col-sm-4"  v-model="emailSuffix" :options="emailOptions"/>
              </q-card-main>
              <q-btn
                  color="primary"
                  push
                  @click="sendCaptchaByEmail"
                  class="full-width"
                  icon="send"
                  loader
                >发送校验</q-btn>
          </q-card>
        </q-collapsible>
      </q-list>

      <q-list>
        <q-list-header>个性设置</q-list-header>
        <q-item tag="label">
          <q-item-side>
            <q-checkbox v-model="checked_one" />
          </q-item-side>
          <q-item-main>
            <q-item-tile label>记录上次操作</q-item-tile>
            <q-item-tile sublabel>开启后，在重新进入应用时，会根据您的操作历史，适当的提醒您快速进入上次的操作</q-item-tile>
          </q-item-main>
        </q-item>

        <q-collapsible  icon="perm phone msg" label="勿扰设置">
          <q-item tag="label">
                <q-item-main>
                  <q-item-tile label>模式</q-item-tile>
                </q-item-main>
                <q-item-side >
                    <q-toggle v-model="disturbToggle" color="secondary" />
                </q-item-side>
          </q-item>
          <q-item v-if="disturbToggle">
               <q-item-main>
                  <q-item-tile label>时间段</q-item-tile>
                </q-item-main>
               <q-item-main >
                  <q-datetime-range color="amber" v-model="disturbTimeRange" type="time" class="full-width" />
                </q-item-main>
          </q-item>
        </q-collapsible>
        <q-item-separator />

        <q-collapsible  icon="stay current portrait" label="系统信息">
          <q-item>
              <table class="q-table striped">
                <thead>
                  <tr>
                    <th class="text-left">属性</th>
                    <th class="text-left">值</th>
                  </tr>
                </thead>

                <tbody>
                  <tr v-for="(value, prop) in platform" :key="prop">
                    <td>{{ prop }}</td>
                    <td>{{ value }}</td>
                  </tr>
                </tbody>
              </table>
          </q-item>
        </q-collapsible>
        <q-item-separator />
      </q-list>
    </div>
  </div>
</template>

<script>
import {
  QDatetimeRange,
  QList,
  QListHeader,
  QItem,
  QItemSeparator,
  QItemSide,
  QItemMain,
  QItemTile,
  QCheckbox,
  QRadio,
  QToggle,
  QSlider,
  QRange,
  QSelect,
  QCard,
  QCardTitle,
  QCardMain,
  QCollapsible,
  QBtn,
  QInput,
  QIcon,
  QField,
  Alert
} from "quasar";
import mobileCaptchaCompo from "../mobile-captcha-compo";
import avatarEditCompo from '../avatar-edit-compo';
import commonApi from "../../../https/commonApi";
import customerApi from "../../../https/customerApi";
import Storage from '../../../utils/storage';
import StorePouch from "../../../utils/StorePouch";

export default {
  components: {
      QDatetimeRange,
      avatarEditCompo,
    mobileCaptchaCompo,
    QList,
    QListHeader,
    QItem,
    QItemSeparator,
    QItemSide,
    QItemMain,
    QItemTile,
    QCheckbox,
    QRadio,
    QToggle,
    QSlider,
    QRange,
    QCard,
    QCardTitle,
    QCardMain,
    QCollapsible,
    QBtn,
    QInput,
    QIcon,
    QField,
    QSelect,
    Alert
  },
  data() {
    return {
      // baseResUpUrl: commonApi.uploadFilesUrlCompress(250, 250), //资源上传路径
      customer: {},
      changePwdDto: {},
      emailSend:null,
      emailSuffix: "@qq.com",
      emailError: false,
      pwdset: null,
      pwdsetError: false,
      originPwdError:false,
      newPwdError:false,
      emailOptions: [
        { label: "@qq.com", value: "@qq.com" },
        { label: "@163.com", value: "@163.com" },
        { label: "@126.com", value: "@126.com" }
      ],
      sexOptions: [
        {
          label: "帅锅",
          value: "帅锅"
        },
        {
          label: "萝莉",
          value: "萝莉"
        },
        {
          label: "美女",
          value: "美女"
        },
        {
          label: "先生",
          value: "先生"
        },
        {
          label: "女士",
          value: "女士"
        },
        {
          label: "大叔",
          value: "大叔"
        },
        {
          label: "大姐",
          value: "大姐"
        },
        {
          label: "大爷",
          value: "大爷"
        },
        {
          label: "大妈",
          value: "大妈"
        }
      ],
      disturbTimeRange: {
        from: null,
        to: null
      },
      disturbToggle: false,
      checked_one: true,
      platform: this.$q.platform.is
    };
  },
  mounted() {
    this.loadData();
  },
  methods: {
    loadData() {
       customerApi
          .userinfo()
          .then(res => {
            const { status, data } = res;
            Storage.saveuser(data);
            if (status == 200 && data) {
              this.customer = data || {};
            }
          })
          .catch(err => {
            Storage.removeCuruser();
          });
    },
    uploadAvatarPic(fileObj){
      if(fileObj) {
        const formData = new FormData();
        formData.append('files',fileObj)
        commonApi.uploadFiles(formData).then(res=>{
          const {status,data} = res;
          if(status == 200 && data) {
            console.log('上传文件得到的文件名：',data);
            this.setLogoResAction(data)
          }
        }).catch(err=>{})
      }
    },
    setLogoResAction(res) {//更改头像
      console.log('更改头像：',res[0]);
      if(!res || !new String(res).startsWith('Error')) {
          const _obj = res[0];
          this.customer.logoRes = _obj;
          customerApi.setLogoRes(_obj).then(res=>{
            if(res.status == 200 ){
              Storage.saveuser(this.customer)
              this.loadData();
            }
          }).catch(err=>{})
      }else {
        console.log('更改头像，图片上传失败');
      }
    },
    updateNickname() {
      customerApi.setNickname(this.customer.nickname).then(res=>{
          if(res.status == 200) {
            Storage.saveuser(this.customer);
            StorePouch.tokenDbUpdate( StorePouch.tokenId(),this.customer.nickname);
            this.alertMsg('昵称更改成功','green')
            this.loadData();
          }
         }).catch(err=>{})
    },
    updateMobile(item) {
      console.log('更改手机号：',item);
      if(item) {
        customerApi.updateBindinfo({bindinfoType:'MOBILE',value:item.mobile,orgValue:item.orgmobile,captcha:item.captcha})
          .then(res=>{
              customerApi.userinfo().then(res=>{
                  if(res.status == 200 ) {
                    let _temp = res.data
                    _temp.commonDevices = null;
                    Storage.saveuser(_temp)
                    this.alertMsg('手机号码更改成功','green')
                    this.loadData();
                  }
                }).catch(err=>{
                console.log('get-userinfo异常');
              })
          })
          .catch(err=>{console.log('更改手机信息绑定异常');})
      }
    },
    setpwd() {
      const _pwdset = this.pwdset;
      if (_pwdset == null || _pwdset.length < 6 || _pwdset.length > 16) {
        this.pwdsetError = true;
        return false;
      }
      this.pwdsetError = false;
      customerApi.setPwd(_pwdset).then(res=>{ 
        if(res.status == 200) {
          this.alertMsg('密码设定成功','green')
          this.loadData();
        }
       }).catch(err=>{})
    },
    updateSex() {
      customerApi.setSex(this.customer.sex).then(res=>{
          if(res.status == 200) {
            Storage.saveuser(this.customer);
            console.log("更改性别");
          }
        }).catch(err=>{})
    },
    updateSummary(){
        customerApi.setSummary(this.customer.summary).then(res=>{
          if(res.status == 200) {
            Storage.saveuser(this.customer);
            this.alertMsg('签名更新成功','green')
            this.loadData();
          }
         }).catch(err=>{})
    },
    changePwdCheckOrg() {//校验原始密码
      if(!this.changePwdDto.originPwd) {
        this.originPwdError = true;
        return false;
      }else {
        this.originPwdError = false;
        return true;
      }
    },
    changePwdCheckNew() {//校验新密码
      const _newPwd = this.changePwdDto.newPwd;
      if (_newPwd == null || _newPwd.length < 6 || _newPwd.length > 16) {
        this.newPwdError = true;
        return false;
      }else {
        this.newPwdError = false;
        return true;
      }
    },
    changePwdAction() {
      if(this.changePwdCheckOrg() && this.changePwdCheckNew()) {
        customerApi.setPwdCheck(this.changePwdDto).then(res=>{
          StorePouch.tokenDbRemove(StorePouch.tokenId());
          this.alertMsg('密码修改成功','green')
          this.loadData();
        }).catch(err=>{})
      }
    },
    checkSendEmail() {
      const _email = this.emailSend;
      if (_email == null || _email.length < 6 || _email.length > 16) {
        this.emailError = true;
        return false;
      } else {
        this.emailError = false;
        return true;
      }
    },
    alertMsg(msg,_type) {
      if(!_type) {_type = 'success'}
      if (msg) {
        const _errAlert = Alert.create({
          color: _type,
          icon: 'info',
          html: msg,
          position: 'bottom',
        });
        setTimeout(()=>{
          _errAlert.dismiss();
        },3000);
      }
    },
    sendCaptchaByEmail(e,done) {
      const {id} = this.customer;
      if (this.checkSendEmail() && id) {
        customerApi.sendValidateEmail({email:this.emailSend+this.emailSuffix,msgType:'BIND_VALIDATE'},id)
          .then(res=>{
            if(res.status == 200) {
              this.alertMsg('邮箱发送成功，请及时验证')
              done();
            }
          }).catch(err=>{
            done();
          })
      }else {
        done();
      }
    }
  }
};
</script>
